package com.mdb.config;

import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mdb.util.PropertiesUtil;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.MongoOptions;

public class MongoDBConfig implements IDBConfig{
	private static final Logger log = LoggerFactory.getLogger(MongoDBConfig.class);
	private static DB db = null;
	private static String reflectPackage;
	private static MongoDBConfig dbConfig;
	
	@Override
	public String getModelReflectPackage() {
		return reflectPackage;
	}
	
	@Override
	public DB getDB() {
		return db;
	}
	
	static {
		try {
			PropertiesUtil.loadConfig(CONFIG_PATH);
			reflectPackage = PropertiesUtil.getString("package");
			String user = PropertiesUtil.getString("user");
			int port = PropertiesUtil.getInt("port");
			String passwd = PropertiesUtil.getString("passwd");
			String host = PropertiesUtil.getString("host");
			String dbName = PropertiesUtil.getString("dbName");
			int poolSize = PropertiesUtil.getInt("poolSize");
			MongoDBConfig.getDBConfig().initialize(host, port, user, passwd, dbName, poolSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 初始化MONGODB
	 * @param host 主机IP
	 * @param port 端口
	 * @param user 用户名
	 * @param passwd 密码
	 * @param dbName 数据库名
	 * @param poolSize 每个主机允许的连接数
	 */
	@Override
	public void initialize(String host, int port, String user, String passwd, String dbName, int poolSize) {
		System.setProperty("MONGO.POOLSIZE", String.valueOf(poolSize));

		Mongo mg = null;
		try {
			mg = new Mongo(host, port);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
		MongoOptions options = mg.getMongoOptions();
		//当连接池被用光时，会被阻塞住
		options.autoConnectRetry = true;

		options.connectionsPerHost = poolSize;
		db = mg.getDB(dbName);
		char[] pwd = passwd.toCharArray();

		if (db.authenticate(user, pwd)) {
			Object[] params = { host, Integer.valueOf(port), dbName, Integer.valueOf(poolSize) };
			log.info("Database connect success-[url={}:{}/{}, pool_size={}]", params);
			return;
		}

		mg.close();
		throw new IllegalArgumentException("Access denied for user '" + user + "'@'" + host + "'");
	}


	public static synchronized IDBConfig getDBConfig() {
		if(dbConfig == null) {
			dbConfig = new MongoDBConfig();
		}
		return dbConfig;
	}
}
